<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>

        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('承租人名称')" prop="lesseeId">
            <template>
              <router-link
                target="_blank"
                :to="{path:'/company/base/companyBaseHome',query:{companyId:form.lesseeId}}"
                class="link_a"
              >{{ form.lesseeName }}
              </router-link>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealName">
            <template>
              <router-link
                target="_blank"
                :to="{path:'/deal/home/dealBaseHome',query:{id:form.dealId}}"
                class="link_a"
              >{{ form.dealName }}
              </router-link>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('账户名称')" prop="accountId">
            <el-select v-model="form.accountId" :placeholder="$t('账户名称')" filterable clearable @change="bankAccount">
              <el-option
                v-for="item in dealBankAccountList"
                :key="item.id"
                :label="$t(item.accountName)"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('开户行')" prop="openingBank">
            <el-input v-model="form.openingBank" :placeholder="$t('开户行')" show-word-limit maxlength="100" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('银行账号')" prop="bankAccount">
            <el-input v-model="form.bankAccount" :placeholder="$t('银行账号')" show-word-limit maxlength="50" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('付款金额')+$t('金额单位')" prop="paymentAmount">
            <Money v-model="form.paymentAmount" :placeholder="$t('付款金额')" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('付款金额大写')" prop="paymentAmountInWords">
            <el-input v-model="form.paymentAmountInWords" :placeholder="$t('付款金额大写')" show-word-limit disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('关联合同')" prop="contractId">
            <div style="display: flex;">
              <el-select v-model="form.contractId" :placeholder="$t('合同名称')" filterable clearable>
                <el-option
                  v-for="item in dealLeaseContractList"
                  :key="item.id"
                  :label="$t(item.actTitle)"
                  :value="item.id"
                />
              </el-select>
              <el-button slot="append" icon="el-icon-view" @click="viewContractPage(form.contractId)" />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('事由')" prop="subjectMatter">
            <el-input v-model="form.subjectMatter" type="textarea" :placeholder="$t('事由')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>

      </el-row>
      <FileTable :list.sync="form.fileList" has-permi="lease:loanRecord" data-type="deal_lease_loan_record" :business-id="form.dealId" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="lease:loanRecord" />
    </div>

    <!-- 添加或修改合同管理对话框 -->
    <el-dialog :title="$t('合同管理')" :visible.sync="contractOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <dealLeaseContractForm ref="dealLeaseContractForm" />
    </el-dialog>
  </div>
</template>

<script>
    import { getDealBase } from '@/api/base/deal/dealBase'
    import {
      amountConversion,
      getDealLeaseLoanRecord,
      saveDealLeaseLoanRecord
    } from '@/api/deal/financing/record/dealLeaseLoanRecord'
    import { listDealLeaseContract } from '@/api/deal/financing/contract/dealLeaseContract'
    import { listDealBankAccount } from '@/api/deal/financingLease/bankAccount/dealBankAccount'
    import dealLeaseContractForm from '../contract/dealLeaseContractForm'
    const { getDealLeaseContract } = require('@/api/deal/financing/contract/dealLeaseContract')
    export default {
        components: {
            dealLeaseContractForm
        },
        data() {
            return {
                // 表单参数
                form: {},
                // 表单校验
                rules: {
                  actTitle: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  openingBank: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  accountId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  bankAccount: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  paymentAmount: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  contractId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  subjectMatter: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                // 遮罩层
                loading: false,
                contractOpen: false,
                // 操作按钮默认不展示
                buttonShow: true,
                // 是否隐藏其它按钮
                otherBtnHide: false,
                // 关联合同下拉
                dealLeaseContractList: [],
                // 银行下拉
                dealBankAccountList: []
            }
        },
        watch: {
          'form.paymentAmount': {
            handler(newValue) {
              if (newValue === '' || newValue === undefined) {
                this.form.paymentAmount = 0
              }
              this.amountConversion(this.form.paymentAmount)
            },
            immediate: true
          }
        },
        created() {
            this.$bus.$emit('async_done')
            listDealLeaseContract({ dealId: this.form.dealId, actStatus: 'W' }).then(response => {
              this.dealLeaseContractList = response.rows
            })
            listDealBankAccount({}).then(response => {
              this.dealBankAccountList = response.rows
            })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getDealLeaseLoanRecord(data.id).then(response => {
                        this.form = response.data
                        this.loading = false
                    }).catch(() => {
                        this.loading = false
                    })
                } else {
                    this.reset()
                    getDealBase(this.$route.query.id).then(response => {
                      this.form.dealName = response.data.dealName
                      this.form.lesseeId = response.data.companyId
                      this.form.lesseeName = response.data.company.companyName
                      this.loading = false
                    }).catch(() => {
                      this.loading = false
                    })
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    dealId: this.$route.query.id,
                    actTitle: undefined,
                    actId: undefined,
                    actStatus: undefined,
                    lesseeId: undefined,
                    lesseeName: undefined,
                    dealName: undefined,
                    openingBank: undefined,
                    accountName: undefined,
                    bankAccount: undefined,
                    paymentAmount: undefined,
                    paymentAmountInWords: undefined,
                    contractId: undefined,
                    subjectMatter: undefined,
                    actualPaymentTime: undefined,
                    actualPaymentAmount: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                    this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm(type) {
                return new Promise((resolve, reject) => {
                  this.$refs['form'].validate(valid => {
                    // 验证数据
                    if (valid) {
                      // 弹出遮罩层
                      this.loading = true
                      // 保存数据
                      saveDealLeaseLoanRecord(this.form).then(response => {
                        if (response.code === 200) {
                          // 点击的按钮是保存并启动流程
                          if (type === 'process') {
                            // 启动流程
                            this.startProcess(response.data)
                            // 点击的仅保存
                          } else {
                            this.msgSuccess(this.$t('保存成功'))
                            // 关闭form页面
                            this.closeForm()
                          }
                          resolve()
                        } else {
                          this.msgError(response.msg)
                          this.loading = false
                          reject()
                        }
                      })
                    } else {
                      reject()
                      this.locationError(document)
                    }
                  })
                }).catch(() => {
                    this.loading = false
                })
           },
            // 启动流程
           startProcess(data) {
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = '[' + data.dealName + ']' + data.actTitle
               // 业务表名
               processData.dataTable = 'deal_lease_loan_record'
               // 业务ID
               processData.dataId = data.id
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/deal/financing/record/dealLeaseLoanRecordForm'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = 'deal_lease_loan_record'
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           },
          bankAccount(index) {
            this.dealBankAccountList.forEach(bank => {
              if (bank.id === index) {
                this.form.openingBank = bank.openingBank
                this.form.bankAccount = bank.bankAccount
              }
            })
          },
          amountConversion(paymentAmount) {
            amountConversion(paymentAmount).then(response => {
              console.log(response.data)
              this.form.paymentAmountInWords = response.data
            })
          },
          viewContractPage(id) {
            if (id !== null && id !== '' && id !== undefined) {
              // 根据合同ID 查出对应的合同
              getDealLeaseContract(id).then(response => {
                this.contractOpen = true
                this.$nextTick(() => {
                  this.$refs.dealLeaseContractForm.init(response.data)
                })
              })
            } else {
              this.msgError(this.$t('请先选择一个合同!'))
            }
          }

        }

    }
</script>
